<?php
declare (strict_types = 1);

namespace app\admin\service;

use app\admin\model\admin\AdminUser;
use app\admin\model\admin\AdminPermission;

/**
 * 管理员模型
 */
class MenuService
{
   public static function getListByUid(int $id)
   {
      $userModel = AdminUser::with('roles')->find($id)->toArray();
      $permissions = [];
      if ($userModel['id'] == 1){
            $perms = AdminPermission::where('status', 1)
            ->order('sort','DESC')
            ->order('id','ASC')
            ->select();
            foreach ($perms as $p){
                $permissions[$p['id']] = [
                    'id'    => $p['id'],
                    'pid'   => $p['pid'],
                    'title' => $p['title'],
                    'href'  => APP_DS_PHP.$p['href'],
                    'icon'  => 'layui-icon '.$p['icon'],
                    'type'  => $p['type'],
                    'sort'  => $p['sort']
                ];
            }
        }else{
            //处理权限
            if (isset($userModel['roles']) && !empty($userModel['roles'])) {
                foreach ($userModel['roles'] as $r) {
                    if ($r['permissions']) {
                        $permission = AdminPermission::where('status', 1)
                        ->order('sort','DESC')
                        ->order('id','ASC')
                        ->whereIn('id',$r['permissions'])
                        ->select();

                        foreach ($permission as $p) 
                        {
                            $permissions[$p['id']] = [
                                    'id'    => $p['id'],
                                    'pid'   => $p['pid'],
                                    'title' => $p['title'],
                                    'href'  => APP_DS_PHP.$p['href'],
                                    'icon'  => 'layui-icon '.$p['icon'],
                                    'type'  => $p['type'],
                                    'sort'  => $p['sort']
                            ];
                            
                        }
                    }
                }
            }
            $key =  array_column( $permissions, 'sort');
            array_multisort($key, SORT_DESC, $permissions);
        }
        //合并权限为用户的最终权限
        return $permissions;
    }
}

